package com.sky.controller.admin;

import com.github.pagehelper.Page;
import com.sky.anno.AutoFill;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     */
    @PostMapping
    public Result add(@RequestBody DishDTO dishDTO){
        dishService.add(dishDTO);
        return Result.success();
    }

    /**
     * 菜品查询分页
     */
    @GetMapping("/page")
    public Result page(DishPageQueryDTO pageQueryDTO){
        PageResult pr = dishService.page(pageQueryDTO);
        return Result.success(pr);
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    // @RequestParam 注解可以动态解析字符串并提取到ids对象中
    public Result delete(@RequestParam List<Long> ids){
        dishService.delete(ids);
        return Result.success();
    }

    /**
     * 修改菜品(根据Id查询菜品 回显)
     */
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        DishVO dishvo = dishService.getById(id);
        return Result.success(dishvo);
    }

    /**
     * 修改菜品 · 真
     */
    @PutMapping
    public Result update (@RequestBody DishDTO dishDTO){
        dishService.update(dishDTO);
        return Result.success();
    }

    /**
     * 根据分类ID查询菜品信息(用于修改套餐时,菜品信息的回显)
     */
    @GetMapping("/list")
    public Result getId(Long categoryId){
        List<Dish> dish = dishService.getId(categoryId);
        return Result.success(dish);
    }

    /**
     * 修改菜品状态
     */
    @PostMapping("/status/{status}")
    public Result status(@PathVariable Integer status , Long id){
        cleanCache("dish_category_*");
        dishService.status(status,id);
        return Result.success();
    }

    /**
     * 根据指定的key样式，删除对应数据
     * @param pattern
     */
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
